/**
 * 矢量模型
 */
import LayerModel from "../LayerModel";
import store from "@/store/store";

export default class VectorLayerModel extends LayerModel {

  constructor(layerInfo){
    super(layerInfo);
    this.layerInfo = layerInfo;

  }

  // 添加图层
  addLayer(){

    let url = this.layerInfo.url;

    // 判断服务是否已经加载
    if(store.state.viewerLayers[url]) {
      console.error(`VectorLayerModel添加图层错误，原因：该影像图层已经存在。url = ${url}。`);
    }

    let layerInfo = this.layerInfo;

    let name = layerInfo.name;

    let mvtLayer;
    if(layerInfo.subdomains) {
      mvtLayer = scene.addVectorTilesMap({
        url: layerInfo.subdomainConfig.urlScheme,
        subdomains: layerInfo.subdomainConfig.subdomains,
        canvasWidth: 512,
        name,
        viewer: viewer
      });
    } else {
      mvtLayer = scene.addVectorTilesMap({
        url,
        canvasWidth: 512,
        name,
        viewer: viewer
      });
    }


    // 图层加载完成
    mvtLayer.readyPromise.then(() => {

      mvtLayer.selectEnabled = false; // 图层不能选择

      let show = layerInfo.show || false; // 图层是否显示
      let alpha = layerInfo.alpha; // 透明度
      mvtLayer.alpha = (alpha || alpha === 0) ? alpha : 1;
      mvtLayer.show = show;

      // 保存当前图层对象到模型
      this.childLayers = mvtLayer;

      // 将对象添加到图层列表中
      store.state.viewerLayers[url] = this;

    }).otherwise(errInfo => {
      console.error(`VectorLayerModel添加图层错误，url = ${url}。原因：${errInfo}。`);
    });
  }

  // 删除图层
  removeLayer(){

    viewer.removeVectorTilesMap(this.layerInfo.name);

    if(store.state.viewerLayers[url]) {
      store.state.viewerLayers[url] = undefined;
      delete store.state.viewerLayers[url];
    }
    return true;
  }

  // 飞行
  flyTo(){

    let isFly = super.flyTo(); // 按配置的坐标飞行

    // 没有在配置文件中定义坐标位置坐标
    if(!isFly) {
      let layer = this.childLayers;
      if(layer) {
        let west = layer.mapboxStyle.metadata.mapbounds[0];
        let south = layer.mapboxStyle.metadata.mapbounds[1];
        let east = layer.mapboxStyle.metadata.mapbounds[2];
        let north = layer.mapboxStyle.metadata.mapbounds[3];
        let rectangle = Cesium.Rectangle.fromDegrees(west, south, east, north);
        let camera = viewer.scene.camera;
        camera.flyTo({
          destination: rectangle
        });
      }
    }
  }

  // 设置图层的可见性
  setVisible(isVisible){
    let layer = this.childLayers;
    if(layer) {
      layer.show = isVisible;
    }
  }
}
